package Concurrency2.Chapter07_Collection.traditional;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 试验目的: 传统并发容器的特点: 并发迭代修改抛出异常.
 * 试验结论: 在jdk11下, 没有抛出异常的问题
 * Author：@author MaLi
 */
public class T01_Characteristic {
    //在迭代过程中不可以对其修改: 添加
    private static Random random = new Random();
    private static CountDownLatch countDownLatch = new CountDownLatch(10);

    public static void main(String[] args) {
        ArrayList<String> notSafeList = new ArrayList<>();
        notSafeList.add("a");
        notSafeList.add("b");

        List<String> synchronizedList = Collections.synchronizedList(notSafeList);
        ExecutorService pool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            pool.submit(new SomeRunnable(synchronizedList));
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(synchronizedList);
        pool.shutdownNow();
    }

    private static class SomeRunnable implements Runnable {
        private List<String> synchronizedList = null;
        private Iterator<String> iterator;

        public SomeRunnable(List<String> synchronizedList) {
            this.synchronizedList = synchronizedList;
            this.iterator = synchronizedList.iterator();
        }

        @Override
        public void run() {
            int turns = 0;
            while (iterator.hasNext()) {
                synchronizedList.add("x" + random.nextInt(5));
                if ((++turns) == 10)
                    break;
            }
            countDownLatch.countDown();
        }
    }
}
